let index = 0;
// 全局Map用于存储题目状态（键为练习ID-question_order，值为状态对象）
const questionStateMap = new Map();
let isFilterListenerAdded = false;
// 生成唯一ID（练习ID-question_order）
function generateQuestionId(practiceId, questionOrder) {
    return `${practiceId}-${questionOrder}`;
}
import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
async function displayIncorrectQuestions(update,reset,scrollPosition = null) {
    try {
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        await setupUserProfile(username);
        // 获取用户ID
        const userResponse = await fetch(`/user-info?username=${username}`);
        const data = await userResponse.json();
        const userId = data.user_id;

        // 获取无法提交的练习ID
        const practiceIdsResponse = await fetch(`/api/get-unsubmittable-practices?userId=${userId}`);
        const practiceIds = await practiceIdsResponse.json();
        //console.log('无法提交的练习ID:', practiceIds);

        // 获取练习名称并填充选择框
        const practiceFilter = document.getElementById('practiceFilter');
        practiceFilter.innerHTML = '<option value="all">全部</option>';
        const practiceNames = {};
        for (const practiceId of practiceIds) {
            const practiceResponse = await fetch(`/practice/detail/${practiceId}`);
            const practiceData = await practiceResponse.json();
            const practiceName = practiceData.practice_name;
            practiceNames[practiceId] = practiceName;
            const option = document.createElement('option');
            option.value = practiceId;
            option.textContent = practiceName;
            practiceFilter.appendChild(option);
        }

        if(update){
        if (reset) {
            // 更新错题信息（插入+更新）
            for (const practiceId of practiceIds) {
                await fetch(`/api/get-incorrect-questions?practiceId=${practiceId}&userId=${userId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ practiceId, userId })
                });
            }
        } else {
            // 仅插入，不更新
            for (const practiceId of practiceIds) {
                await fetch(`/api/get-incorrect-questions-only-insert?practiceId=${practiceId}&userId=${userId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ practiceId, userId })
                });
            }
        }
        }
        // 获取错题详细信息
        const incorrectQuestionsResponse = await fetch('/api/get-all-incorrect-questions');
        const incorrectQuestions = await incorrectQuestionsResponse.json();
        // 显示错题
        const questionsContainer = document.getElementById('questionsContainer');
        questionsContainer.innerHTML = '';

        // 合并所有题目
        const allQuestions = [
            ...incorrectQuestions.choiceQuestions,
            ...incorrectQuestions.fillQuestions
        ];

        // 按练习ID和题目类型排序
        allQuestions.sort((a, b) => {
            const practiceCompare = a.practice_id.localeCompare(b.practice_id);
            if (practiceCompare !== 0) return practiceCompare;
            
            const typeOrder = { 'choice': 1, 'fill': 2 };
            return typeOrder[a.question_type] - typeOrder[b.question_type];
        });

        index = 0;
        if(!isFilterListenerAdded){
        // 添加选择框的change事件监听器
        practiceFilter.addEventListener('change', () => {
            const selectedPracticeId = practiceFilter.value;
            questionsContainer.innerHTML = '';
            index = 0;
            for (const question of allQuestions) {
                if (selectedPracticeId === 'all' || question.practice_id === selectedPracticeId) {
                    switch (question.type) {
                        case 'choice':
                            displaySingleChoiceQuestion(question, questionsContainer, userId);
                            break;
                        case 'fill':
                            displaySingleFillQuestion(question, questionsContainer, userId);
                            break;
                    }
                }
            }
        });
        isFilterListenerAdded = true;
        }
        //console.log('allQuestions:', allQuestions);
        if(allQuestions.length === 0){
            showNoIncorrectQuestions();
            return;
        }
        // 按排序后的顺序显示所有题目
        for (const question of allQuestions) {
            switch (question.type) {
                case 'choice':
                    await displaySingleChoiceQuestion(question,questionsContainer, userId);
                    break;
                case 'fill':
                    await displaySingleFillQuestion(question, questionsContainer, userId);
                    break;
            }
        }
        if (scrollPosition !== null) {
                    setTimeout(() =>{
                        window.scrollTo(0, scrollPosition);
                    }, 50);
        }
    } catch (error) {
        console.error('加载错题失败:', error);
        alert(`加载错题失败: ${error.message}`);
    }
}

// 显示选择题（带选项选择功能）
async function displaySingleChoiceQuestion(question, container, userId) {
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card relative';
    const questionId = generateQuestionId(question.practice_id, question.question_order);
    questionCard.dataset.questionId = questionId;
    // 从Map中获取保存的选项状态
    const savedState = questionStateMap.get(questionId);
    const savedSelectedOption = savedState?.selectedOption;

    // 获取练习名称
    const practiceResponse = await fetch(`/practice/detail/${question.practice_id}`);
    const practiceData = await practiceResponse.json();
    const practiceName = practiceData.practice_name;
    
    // 获取剩余尝试次数
    const maxCorrectTimesResponse = await fetch(`/api/get-incorrect-question-attempts?practice_id=${question.practice_id}&user_id=${userId}&question_order=${question.question_order}`);
    const maxCorrectTimesData = await maxCorrectTimesResponse.json();
    const maxCorrectTimes = maxCorrectTimesData.max_correct_times;
    // 格式化选项
    const options = ['A', 'B', 'C', 'D'];
    let optionsHtml = '';
    let selectedOption = null; // 记录选中的选项
    
    options.forEach(option => {
        // 选项前缀图标（默认未选中）
        const statusIcon = `
            <span class="inline-flex items-center justify-center w-5 h-5 rounded-full border-2 border-gray-300 text-gray-600 mr-2 text-xs transition-colors">
                <i class="fa fa-circle-o text-gray-400 scale-75 hidden"></i>
            </span>
        `;
        
        // 选项字母
        const optionLabel = `<span class="font-medium mr-1">${option}.</span>`;
        
        // 构建选项HTML（添加点击事件）
        optionsHtml += `
            <div class="mb-3 p-3 rounded-md hover:bg-gray-50 transition-all duration-300 flex items-start cursor-pointer option-item" data-option="${option}">
                ${statusIcon}
                <div class="flex-1">
                    <div class="flex items-start">
                        <p>${optionLabel}${escapeHTML(question[`option_${option.toLowerCase()}`])}</p>
                    </div>
                </div>
            </div>
        `;
    });

    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-blue-50 rounded-xl border border-blue-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">选择题</h3>
            <span class="bg-white text-blue-600 rounded-full px-3 py-1 text-sm font-medium">${index + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
            ${escapeHTML(question.question)}
        </div>
        
        <ul class="space-y-3">
            ${options.map(option => `
            <li class="option-item flex items-start bg-white/80 p-3 rounded-lg border border-blue-100 cursor-pointer" data-option="${option}">
                <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">${option}</span>
                <span>${question[`option_${option.toLowerCase()}`]}</span>
            </li>
            `).join('')}
        </ul>
    </div>
    
    <!-- 底部信息栏 -->
    <div class="bg-blue-50/70 px-6 py-4 border-t border-blue-100">
        <div class="flex items-center mb-2">
            <i class="fa-solid fa-book text-blue-500 mr-2"></i>
            <span class="text-gray-600">所属练习：</span>
            <span class="ml-1 font-medium text-blue-700">${escapeHTML(practiceName)}</span>
        </div>
        <div class="flex items-center">
            <span class="text-gray-600">再答对 </span>
            <span class="ml-1 mr-1 text-primary font-bold">${maxCorrectTimes}</span>
            <span class="text-gray-600">次该题目自动移除</span>
        </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="flex justify-center space-x-4 p-4">
        <button class="delete-question-btn flex items-center px-4 py-2 bg-red-500 text-white rounded-lg shadow hover:shadow-md transition-all duration-200 hover:bg-red-600">
            <i class="fa fa-trash-can mr-2"></i> 删除
        </button>
        <button class="judge-question-btn flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg shadow hover:shadow-md transition-all duration-200 hover:bg-blue-600">
            <i class="fa fa-check mr-2"></i> 提交
        </button>
    </div>
</div>
`;

    // 添加选项点击事件
const optionItems = Array.from(questionCard.querySelectorAll('.option-item'));
optionItems.forEach(item => {
    item.addEventListener('click', (e) => {
        const selectedOption = e.currentTarget.dataset.option;
        
        // 重置所有选项样式和选中状态
        optionItems.forEach(opt => {
            opt.classList.remove('bg-blue-200', 'border-blue-500', 'shadow-md'); // 移除高亮样式
            opt.classList.add('bg-white/80', 'border-blue-100'); // 恢复默认样式
            delete opt.dataset.selected; // 清除选中状态
        });
        
        // 设置当前选项为高亮样式
        item.classList.remove('bg-white/80', 'border-blue-100');
        item.classList.add('bg-blue-200', 'border-blue-500', 'shadow-md'); // 添加高亮背景和阴影
        
        // 记录选中的选项
        item.dataset.selected = "true";
        questionStateMap.set(questionId, { selectedOption });
    });
});

if (savedSelectedOption) {
    // 重置所有选项样式和选中状态
    optionItems.forEach(opt => {
        opt.classList.remove('bg-blue-200', 'border-blue-500', 'shadow-md'); // 移除高亮样式
        opt.classList.add('bg-white/80', 'border-blue-100'); // 恢复默认样式
        delete opt.dataset.selected;
    });
    
    // 设置保存的选项
    const selectedItem = optionItems.find(item => item.dataset.option === savedSelectedOption);
    if (selectedItem) {
        selectedItem.classList.remove('bg-white/80', 'border-blue-100');
        selectedItem.classList.add('bg-blue-200', 'border-blue-500', 'shadow-md'); // 添加高亮背景和阴影
        selectedItem.dataset.selected = "true";
    }
}
    // 添加删除按钮点击事件
    const deleteBtn = questionCard.querySelector('.delete-question-btn');
    deleteBtn.addEventListener('click', async () => {
        if (confirm('确定要删除这道错题吗？')) {
            try {
                const response = await fetch('/api/delete-incorrect-question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        practice_id: question.practice_id,
                        user_id: userId,
                        question_order: question.question_order
                    })
                });
            
            const data = await response.json();
            if (data.success) {
                alert('错题已删除');
                // 刷新错题列表
                await displayIncorrectQuestions(false,false);
            } else {
                alert(data.message || '删除失败');
            }
            } catch (error) {
                console.error('删除错题请求失败:', error);
                alert('删除错题请求失败');
            }
        }
    });

    // 显示选择题（带选项选择功能）
    const judgeBtn = questionCard.querySelector('.judge-question-btn');
    judgeBtn.addEventListener('click', async () => {
        // 检查是否已选择选项
const selectedItem = Array.from(optionItems).find(item => {
    // 获取当前问题ID对应的状态
    const state = questionStateMap.get(questionId);
    // 只有当状态存在且当前选项被标记为选中时才返回
    return state && state.selectedOption === item.dataset.option;
});
        if (!selectedItem) {
            alert('请先选择一个选项');
            return;
        }
        
        try {
            // 立即禁用按钮，防止重复提交
            disableControlButtons();
            judgeBtn.disabled = true;
            judgeBtn.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200');
            judgeBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 提交中...';
            questionStateMap.delete(questionId);//若提交，清除状态
            const userAnswer = selectedItem.dataset.option;
            const choiceQuestionResponse = await fetch(`/api/practice/${question.practice_id}/choice-question/${question.question_order}`);
            const choiceQuestionData = await choiceQuestionResponse.json();
            const correctAnswer = choiceQuestionData.data.correct_answer;
            
            // 创建结果容器
            const resultContainer = document.createElement('div');
            resultContainer.className = `mt-4 p-3 rounded-md transition-all duration-500 ${
                userAnswer === correctAnswer ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
            }`;
            
            // 准备结果内容
            let resultHtml = `
                <div class="flex items-start">
                    <i class="fa fa-${userAnswer === correctAnswer ? 'check-circle' : 'times-circle'} mr-2 mt-0.5 text-xl"></i>
                    <div>
                        <p class="font-medium">${userAnswer === correctAnswer ? '回答正确！' : '回答错误！'}</p>
                        <p class="text-sm mt-1">
                            你的选择: ${userAnswer}
                        </p>
                    </div>
                </div>
            `;
            
            // 添加结果容器
            resultContainer.innerHTML = resultHtml;
            questionCard.appendChild(resultContainer);

            // 高亮显示正确和错误的选项
optionItems.forEach(item => {
    const option = item.dataset.option;
    
    if (option === correctAnswer) {
        // 正确答案标绿
        item.classList.add('bg-green-50', 'border-green-500');
    } else if (option === userAnswer) {
        // 错误答案标红
        item.classList.add('bg-red-50', 'border-red-500');
    }
});
            
            // 如果回答正确，处理正确次数
            if (userAnswer === correctAnswer) {
                if (maxCorrectTimes > 1) {
                    // 更新正确次数
                    const updateResponse = await fetch(`/api/update-correct-times`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            practice_id: question.practice_id,
                            user_id: userId,
                            question_order: question.question_order
                        })
                    });
                    
                    const updateData = await updateResponse.json();
                    if (!updateData.success) {
                        throw new Error('更新正确次数失败');
                    }
                } else {
                    // 达到3次正确，删除错题
                    const deleteResponse = await fetch('/api/delete-incorrect-question', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            practice_id: question.practice_id,
                            user_id: userId,
                            question_order: question.question_order
                        })
                    });
                    
                    const deleteData = await deleteResponse.json();
                    if (!deleteData.success) {
                        throw new Error('删除错题失败');
                    }
                }
                // 显示剩余次数信息
                const remainingTimes = maxCorrectTimes > 1 ? maxCorrectTimes - 1 : 0;
                const remainingInfo = document.createElement('div');
                remainingInfo.className = 'mt-2 text-sm text-gray-600';
                remainingInfo.textContent = remainingTimes > 0 
                    ? `再答对${remainingTimes}次该题目自动移除` 
                    : '恭喜！该题目已从错题库中移除';
                questionCard.appendChild(remainingInfo);
                } else {
                    // 回答错误，添加重试提示
                    const retryInfo = document.createElement('div');
                    retryInfo.className = 'mt-2 text-sm text-gray-600';
                    retryInfo.textContent = '请仔细思考后再尝试作答！';
                    questionCard.appendChild(retryInfo);
                }
                
                // 添加倒计时显示
                const countdownContainer = document.createElement('div');
                countdownContainer.className = 'mt-2 text-xs text-gray-500';
                countdownContainer.textContent = '页面将在 5 秒后自动刷新...';
                questionCard.appendChild(countdownContainer);
                
                // 倒计时功能
                let countdown = 5;
                const countdownInterval = setInterval(() => {
                    countdown--;
                    countdownContainer.textContent = `页面将在 ${countdown} 秒后自动刷新...`;
                    
                    if (countdown <= 0) {
                        clearInterval(countdownInterval);
                    }
                }, 1000);
                
                // 5秒后刷新页面
                setTimeout(async () => {
                    try {
                        // 添加刷新前的视觉反馈
                        resultContainer.style.opacity = '0.5';

                        // 保存当前滚动位置
                        const scrollPosition = window.scrollY;
                        
                        // 执行刷新
                        await displayIncorrectQuestions(false, false,scrollPosition);
                        enableControlButtons();
                    } catch (error) {
                        console.error('刷新错题列表失败:', error);
                        // 恢复结果容器的显示
                        resultContainer.style.opacity = '1';
                        countdownContainer.textContent = '刷新失败，请手动刷新页面';
                        countdownContainer.classList.add('text-red-500');
                    }
                }, 5000); 
        } catch (error) {
            console.error('提交答案失败:', error);
            alert(`提交答案失败: ${error.message}`);
            
            // 恢复按钮状态，允许用户重试
            judgeBtn.disabled = false;
            judgeBtn.classList.remove('opacity-50', 'cursor-not-allowed', 'bg-gray-200');
            judgeBtn.innerHTML = '<i class="fa fa-check-circle mr-1"></i> 提交';
            enableControlButtons();
        }
    });
    
    // 将问题卡片添加到容器
    container.appendChild(questionCard);
    index++;
}

// 显示填空题（输入框在题目下方展示）
async function displaySingleFillQuestion(question, container, userId) {
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card relative';
    const questionId = generateQuestionId(question.practice_id, question.question_order);
    questionCard.dataset.questionId = questionId;
    // 获取练习名称
    const practiceResponse = await fetch(`/practice/detail/${question.practice_id}`);
    const practiceData = await practiceResponse.json();
    const practiceName = practiceData.practice_name;
    // 从Map中获取保存的填空答案
    const savedState = questionStateMap.get(questionId);
    const savedAnswers = savedState?.answers || {};
    // 获取剩余尝试次数
    const maxCorrectTimesResponse = await fetch(`/api/get-incorrect-question-attempts?practice_id=${question.practice_id}&user_id=${userId}&question_order=${question.question_order}`);
    const maxCorrectTimesData = await maxCorrectTimesResponse.json();
    const maxCorrectTimes = maxCorrectTimesData.max_correct_times;
    // 解析填空题的空
    let blankCount = 0;
    const originalQuestion = escapeHTML(question.question); // 保存原始题目文本

    const blanks = []; // 存储每个空的信息
    
    // 计算空白数量
    const questionText = originalQuestion.replace(/__/g, (match, index) => {
        blankCount++;
        blanks.push({ index: blankCount });
        return `__`; // 保留原题中的空白标记
    });
    const formattedQuestion = originalQuestion.replace(/__/g, 
        '<span class="inline-block mx-1 px-3 py-1 bg-green-50 border border-green-200 rounded text-sm">填空</span>'
    );
    // 生成填空输入框HTML
     
// 生成填空输入框HTML
let blanksInputHtml = '';
for (let i = 1; i <= blankCount; i++) {
    blanksInputHtml += 
`
            <div class="mb-3 flex items-center">
                <span class="w-10 text-gray-600">空${i}:</span>
                <input type="text" class="blank-input ml-2 px-3 py-2 rounded-md bg-green-50 text-gray-700 border border-green-200 focus:ring-2 focus:ring-green-500/50 focus:bg-white" 
                       placeholder="请输入答案" data-blank="${i}">
            </div>
        `;
    }

    questionCard.
innerHTML = 
`
<div class="bg-gradient-to-br from-white to-green-50 rounded-xl border border-green-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-green-500 to-green-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">填空题</h3>
            <span class="bg-white text-green-600 rounded-full px-3 py-1 text-sm font-medium">
${index + 1}
</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-6 leading-relaxed">
            ${formattedQuestion}
        </div>
        
        <div class="answer-section">
            <div class="answer-label text-gray-600 font-medium mb-3">填空答案：</div>
            ${blanksInputHtml}
        </div>
    </div>
    
    <!-- 底部信息栏 -->
    <div class="bg-green-50/70 px-6 py-4 border-t border-green-100">
        <div class="flex items-center mb-2">
            <i class="fa-solid fa-book text-green-500 mr-2"></i>
            <span class="text-gray-600">所属练习：</span>
            <span class="ml-1 font-medium text-green-700">
${escapeHTML(practiceName)}
</span>
        </div>
        <div class="flex items-center">
            <span class="text-gray-600">再答对 </span>
            <span class="ml-1 mr-1 text-primary font-bold">
${maxCorrectTimes}
</span>
            <span class="text-gray-600">次该题目自动移除</span>
        </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="flex justify-center space-x-4 p-4">
        <button class="delete-question-btn flex items-center px-4 py-2 bg-red-500 text-white rounded-lg shadow hover:shadow-md transition-all duration-200 hover:bg-red-600">
            <i class="fa fa-trash-can mr-2"></i> 删除
        </button>
        <button class="judge-question-btn flex items-center px-4 py-2 bg-green-500 text-white rounded-lg shadow hover:shadow-md transition-all duration-200 hover:bg-green-600">
            <i class="fa fa-check mr-2"></i> 提交
        </button>
    </div>
</div>
    `
;

    // 添加输入事件（保存答案到Map）
    const blankInputs = questionCard.querySelectorAll('.blank-input');
    blankInputs.forEach(input => {
        const blankNum = input.dataset.blank;
        input.addEventListener('input', () => {
            const answers = { ...savedAnswers, [blankNum]: input.value };
            questionStateMap.set(questionId, { answers });
        });
    });
    
    // 恢复保存的填空答案
    Object.entries(savedAnswers).forEach(([blankNum, value]) => {
        const input = questionCard.querySelector(`[data-blank="${blankNum}"]`);
        if (input) input.value = value;
    });

    //提交answer
    const judgeBtn = questionCard.querySelector('.judge-question-btn');
    judgeBtn.addEventListener('click', async () => {
        // 检查空是否填完整了
        let allFilled = true;
        blankInputs.forEach(input => {
            const value = input.value.trim();
            if (!value.trim()) {
                allFilled = false;
                input.classList.add('border-red-500', 'bg-red-50');
                setTimeout(() => {
                    input.classList.remove('border-red-500', 'bg-red-50');
                }, 1000);
            }
        });
        
        if (!allFilled) {
            alert('请填写所有空！');
            judgeBtn.disabled = false;
            return;
        }
        questionStateMap.delete(questionId);//若提交，清除状态
        try {
            disableControlButtons();
            // 立即禁用按钮，防止重复提交
            judgeBtn.disabled = true;
            judgeBtn.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200');
            judgeBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 提交中...';
            questionStateMap.delete(questionId);//若提交，清除状态
            const fillQuestionResponse = await fetch(`/api/practice/${question.practice_id}/fill-question/${question.question_order}`);
            const fillQuestionData = await fillQuestionResponse.json();
            //获取用户作答的答案
            const userAnswers = {};
            blankInputs.forEach(input => {
                userAnswers[input.dataset.blank] = input.value.trim();
            });

            let isAllCorrect = true;
            const blankResults = [];
            for (let i = 1; i <= blankCount; i++) {
                const userAnswer = userAnswers[i] || '';
                const correctAnswerKey = `blank${i}_answer`;
                const correctAnswer = (fillQuestionData.data[correctAnswerKey]||'').trim();
                const isCorrect = userAnswer === correctAnswer;
                
                //console.log(`空${i}  用户答案：${userAnswer}  正确答案：${correctAnswer}  结果：${isCorrect}`);

                blankResults.push({
                    blankNum: i,
                    userAnswer,
                    correctAnswer,
                    isCorrect
                });
                
                if (!isCorrect) {
                    isAllCorrect = false;
                }
            }
            
            // 创建结果容器
            const resultContainer = document.createElement('div');
            resultContainer.className = `mt-4 p-3 rounded-md transition-all duration-500 ${
                isAllCorrect ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
            }`;
            
            // 准备结果内容（包含详细空的对比）            
            let resultHtml = `
                <div class="flex items-start">
                    <i class="fa fa-${isAllCorrect ? 'check-circle' : 'times-circle'} mr-2 mt-0.5 text-xl"></i>
                    <div>
                        <p class="font-medium">${isAllCorrect ? '回答正确！' : '回答错误！'}</p>
                    </div>
                </div>
            `;
            
            // 添加每个空的详细结果            
            if (!isAllCorrect) {                
                resultHtml += `
                    <div class="mt-3 space-y-2">                        
                        ${blankResults.map(detail => `
                            <div class="flex items-center">
                                <span class="w-10 text-gray-600">空${detail.blankNum}:</span>
                                <span class="${detail.isCorrect ? 'text-green-600' : 'text-red-600 font-medium'}">                                    
                                    ${detail.isCorrect ? '正确' : '错误'}
                                </span>                                
                            </div>
                        `).join('')}
                    </div>
                `;
            }
            // 添加结果容器
            resultContainer.innerHTML = resultHtml;
            questionCard.appendChild(resultContainer);

             // 高亮显示正确/错误的空
             blankResults.forEach(detail => {
                const input = questionCard.querySelector(`[data-blank="${detail.blankNum}"]`);
                if (input) {
                    input.classList.remove('border-green-500', 'bg-green-50', 'border-red-500', 'bg-red-50');
                    if (detail.isCorrect) {
                        input.classList.add('border-green-500', 'bg-green-50'); // 正确空标绿
                    } else {
                        input.classList.add('border-red-500', 'bg-red-50'); // 错误空标红
                    }
                }
            });
            
            // 如果回答正确，处理正确次数
            if (isAllCorrect) {
                if (maxCorrectTimes > 1) {
                    // 更新正确次数
                    const updateResponse = await fetch(`/api/update-correct-times`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            practice_id: question.practice_id,
                            user_id: userId,
                            question_order: question.question_order
                        })
                    });
                    
                    const updateData = await updateResponse.json();
                    if (!updateData.success) {
                        throw new Error('更新正确次数失败');
                    }
                } else {
                    // 达到3次正确，删除错题
                    const deleteResponse = await fetch('/api/delete-incorrect-question', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            practice_id: question.practice_id,
                            user_id: userId,
                            question_order: question.question_order
                        })
                    });
                    
                    const deleteData = await deleteResponse.json();
                    if (!deleteData.success) {
                        throw new Error('删除错题失败');
                    }
                }
                // 显示剩余次数信息
                const remainingTimes = maxCorrectTimes > 1 ? maxCorrectTimes - 1 : 0;
                const remainingInfo = document.createElement('div');
                remainingInfo.className = 'mt-2 text-sm text-gray-600';
                remainingInfo.textContent = remainingTimes > 0 
                    ? `再答对${remainingTimes}次该题目自动移除` 
                    : '恭喜！该题目已从错题库中移除';
                questionCard.appendChild(remainingInfo);

                } else {
                    // 回答错误，添加重试提示
                    const retryInfo = document.createElement('div');
                    retryInfo.className = 'mt-2 text-sm text-gray-600';
                    retryInfo.textContent = '请仔细思考后再尝试作答！';
                    questionCard.appendChild(retryInfo);
                }
                
                // 添加倒计时显示
                const countdownContainer = document.createElement('div');
                countdownContainer.className = 'mt-2 text-xs text-gray-500';
                countdownContainer.textContent = '页面将在 5 秒后自动刷新...';
                questionCard.appendChild(countdownContainer);

                // 倒计时功能
                let countdown = 5;
                const countdownInterval = setInterval(() => {
                    countdown--;
                    countdownContainer.textContent = `页面将在 ${countdown} 秒后自动刷新...`;
                    
                    if (countdown <= 0) {
                        clearInterval(countdownInterval);
                    }
                }, 1000);
                
                // 5秒后刷新页面
                setTimeout(async () => {
                    try {
                        // 添加刷新前的视觉反馈
                        resultContainer.style.opacity = '0.5';

                        // 保存当前滚动位置
                        const scrollPosition = window.scrollY;
                        
                        // 执行刷新
                        await displayIncorrectQuestions(false, false,scrollPosition);
                        enableControlButtons();
                    } catch (error) {
                        console.error('刷新错题列表失败:', error);
                        // 恢复结果容器的显示
                        resultContainer.style.opacity = '1';
                        countdownContainer.textContent = '刷新失败，请手动刷新页面';
                        countdownContainer.classList.add('text-red-500');
                    }
                }, 5000); 
        } catch (error) {
            console.error('提交答案失败:', error);
            alert(`提交答案失败: ${error.message}`);
            
            // 恢复按钮状态，允许用户重试
            judgeBtn.disabled = false;
            judgeBtn.classList.remove('opacity-50', 'cursor-not-allowed', 'bg-gray-200');
            judgeBtn.innerHTML = '<i class="fa fa-check-circle mr-1"></i> 提交';
            enableControlButtons();
        }
    });

    // 添加删除按钮点击事件
    const deleteBtn = questionCard.querySelector('.delete-question-btn');
    deleteBtn.addEventListener('click', async () => {
        if (confirm('确定要删除这道错题吗？')) {
            try {
                const response = await fetch('/api/delete-incorrect-question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        practice_id: question.practice_id,
                        user_id: userId,
                        question_order: question.question_order
                    })
                });
            
            const data = await response.json();
            if (data.success) {
                alert('错题已删除');
                // 刷新错题列表
                // 保存当前滚动位置
                const scrollPosition = window.scrollY;
                // 刷新并传递滚动位置
                await displayIncorrectQuestions(false, false, scrollPosition);
            } else {
                alert(data.message || '删除失败');
            }
            } catch (error) {
                console.error('删除错题请求失败:', error);
                alert('删除错题请求失败');
            }
        }
    });
    // 将问题卡片添加到容器
    container.appendChild(questionCard);
    index++;
}

// 重置错题按钮点击事件
const resetIncorrectQuestionsBtn = document.getElementById('resetIncorrectQuestionBtn');
resetIncorrectQuestionsBtn.addEventListener('click', async () => {
    const modal = document.getElementById('resetIncorrectQuestionModal');
    modal.style.opacity = '1';
    modal.style.pointerEvents = 'auto';
    
    // 确定按钮点击事件                    
    const confirmBtn = document.getElementById('confirmResetIncorrectQuestionBtn');                    
    confirmBtn.addEventListener('click', async () => {                        
        await displayIncorrectQuestions(true,true);
        modal.style.opacity = '0';
        modal.style.pointerEvents = 'none';
    });
    
    // 取消按钮点击事件                    
    const cancelBtn = document.getElementById('cancelResetIncorrectQuestionBtn');                    
    cancelBtn.addEventListener('click', () => {                        
        modal.style.opacity = '0';
        modal.style.pointerEvents = 'none';
    });
    
    // 关闭模态框按钮点击事件                    
    const closeModalBtn = document.getElementById('closeResetIncorrectQuestionModalBtn');                    
    closeModalBtn.addEventListener('click', () => {                        
        modal.style.opacity = '0';
        modal.style.pointerEvents = 'none';
    });
});

const getIncorrectQuestionsBtn = document.getElementById('getRecentIncorrectQuestionBtn');
getIncorrectQuestionsBtn.addEventListener('click', async () => {
    await displayIncorrectQuestions(true,false);
});

// 页面加载时显示错题
window.addEventListener('load', async () => {
    await displayIncorrectQuestions(false,false);
});

// 添加辅助函数来禁用按钮
function disableControlButtons() {
    resetIncorrectQuestionsBtn.disabled = true;
    resetIncorrectQuestionsBtn.classList.add('opacity-50', 'cursor-not-allowed');
    getIncorrectQuestionsBtn.disabled = true;
    getIncorrectQuestionsBtn.classList.add('opacity-50', 'cursor-not-allowed');
}

// 添加辅助函数来启用按钮
function enableControlButtons() {
    resetIncorrectQuestionsBtn.disabled = false;
    resetIncorrectQuestionsBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    getIncorrectQuestionsBtn.disabled = false;
    getIncorrectQuestionsBtn.classList.remove('opacity-50', 'cursor-not-allowed');
}

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='todo-practice.html'+window.location.search;
        });
    }
});

document.getElementById('back-btn').addEventListener('click', () => {
    window.location.href = 'todo-practice.html' + window.location.search;
});

document.getElementById('backBtn').addEventListener('click', () => {
    window.location.href = 'todo-practice.html' + window.location.search;
});

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='todo-practice.html'+window.location.search;
        });
    }
});

// 在question-review.js中添加以下函数
function showNoIncorrectQuestions() {
    const questionsContainer = document.getElementById('questionsContainer');
    questionsContainer.innerHTML = `
        <div class="empty-state text-center py-12">
            <div class="mx-auto w-24 h-24 rounded-full bg-gray-100 flex items-center justify-center mb-6">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
            </div>
            <h3 class="text-xl font-medium text-white mb-2">未找到错题记录</h3>
            <p class="text-white mb-6">您目前没有需要重做的错题，可以尝试重置错题</p>
            <div class="flex justify-center space-x-4">
                <button id="goBackToPracticeBtn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors">
                    <i class="fa-solid fa-arrow-left mr-2"></i> 返回练习列表
                </button>
                <button id="resetIncorrectBtn" class="px-4 py-2 bg-secondary text-white rounded-lg hover:bg-green-600 transition-colors">
                    <i class="fa-solid fa-rotate-right mr-2"></i> 重置错题
                </button>
            </div>
        </div>
    `;

    // 添加返回练习列表按钮事件
    document.getElementById('goBackToPracticeBtn').addEventListener('click', () => {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        window.location.href = `/todo-practice.html?username=${username}`;
    });

    // 添加重置错题按钮事件
    document.getElementById('resetIncorrectBtn').addEventListener('click', () => {
        document.getElementById('resetIncorrectQuestionBtn').click();
    });
}

function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/[&<>"']/g, function (match) {
        switch (match) {
            case '&':
                return '&amp;';
            case '<':
                return '&lt;';
            case '>':
                return '&gt;';
            case '"':
                return '&quot;';
            case "'":
                return '&#039;';
        }
    });
}

export {
  displayIncorrectQuestions,
  displaySingleChoiceQuestion,
  displaySingleFillQuestion,
  showNoIncorrectQuestions,
  escapeHTML,
  generateQuestionId,
  questionStateMap, // 导出全局变量
  index,
  isFilterListenerAdded
};

